<template>
    <div class="page-container" v-loading="loading">
        <el-page-header @back="goBack" :content="'策略详情: ' + (strategy.name || '')">
            <template #extra>
                <el-button type="primary" @click="openBacktestDialog">执行回测</el-button>
            </template>
        </el-page-header>

        <el-card class="mt-4">
            <template #header>基本信息</template>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="ID">{{ strategy.id }}</el-descriptions-item>
                <el-descriptions-item label="策略名称">{{ strategy.name }}</el-descriptions-item>
                <el-descriptions-item label="类型">{{ strategy.type }}</el-descriptions-item>
                <el-descriptions-item label="风险等级">{{ strategy.riskLevel }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getStatusTagType(strategy.status)">{{ strategy.status }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="业绩基准">{{ strategy.benchmark }}</el-descriptions-item>

                <el-descriptions-item label="再平衡规则类型" :span="2" v-if="strategy.rebalanceRule">
                    {{ strategy.rebalanceRule.type === 'PERIODIC' ? '周期调仓' : '阈值调仓' }}
                </el-descriptions-item>
                <el-descriptions-item label="调仓频率"
                    v-if="strategy.rebalanceRule && strategy.rebalanceRule.type === 'PERIODIC'">
                    {{ strategy.rebalanceRule.frequency }}
                </el-descriptions-item>
                <el-descriptions-item label="调仓阈值(%)"
                    v-if="strategy.rebalanceRule && strategy.rebalanceRule.type === 'THRESHOLD'">
                    {{ strategy.rebalanceRule.threshold }}
                </el-descriptions-item>

                <el-descriptions-item label="适用人群" :span="2">{{ strategy.targetAudience }}</el-descriptions-item>
                <el-descriptions-item label="描述" :span="2">{{ strategy.description }}</el-descriptions-item>
                <el-descriptions-item label="拒绝原因" v-if="strategy.rejectionReason">
                    {{ strategy.rejectionReason }}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card class="mt-4">
            <template #header>成分基金</template>
            <el-table :data="strategy.components" style="width: 100%" border>
                <el-table-column prop="fund.code" label="基金代码"></el-table-column>
                <el-table-column prop="fund.name" label="基金名称"></el-table-column>
                <el-table-column prop="fund.type" label="基金类型"></el-table-column>
                <el-table-column prop="weight" label="权重(%)"></el-table-column>
            </el-table>
        </el-card>

        <el-card class="mt-4">
            <template #header>表现</template>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-statistic title="今日收益率 (%)" :value="todayProfit * 100" :precision="2">
                        <template #prefix>
                            <span :style="{ color: getProfitColor(todayProfit) }">
                                {{ todayProfit > 0 ? '+' : '' }}
                            </span>
                        </template>
                    </el-statistic>
                </el-col>
                <el-col :span="8">
                    <el-statistic title="累计收益率 (%)" :value="cumulativeProfit * 100" :precision="2">
                        <template #prefix>
                            <span :style="{ color: getProfitColor(cumulativeProfit) }">
                                {{ cumulativeProfit > 0 ? '+' : '' }}
                            </span>
                        </template>
                    </el-statistic>
                </el-col>
                <el-col :span="8">
                    <el-statistic title="今日成交率 (%)" :value="todayTurnoverRate" :precision="2"></el-statistic>
                </el-col>
            </el-row>
        </el-card>

        <el-card class="mt-4">
            <template #header>调仓历史</template>
            <el-table :data="adjustments" style="width: 100%" border>
                <el-table-column prop="createdAt" label="调仓日期"></el-table-column>
                <el-table-column prop="reason" label="调仓原因"></el-table-column>
                <el-table-column label="详情">
                    <template #default="scope">
                        <ul>
                            <li v-for="detail in scope.row.details" :key="detail.fundCode">
                                基金 {{ detail.fundCode }}: 权重从 {{ detail.fromWeight }}% 变为 {{ detail.toWeight }}%
                            </li>
                        </ul>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <BacktestDialog v-model:visible="backtestDialogVisible" :strategy-id="strategy.id" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
    getStrategyById,
    getAdjustmentHistory,
    getTodayProfit,
    getCumulativeProfit,
    getTodayTurnoverRate
} from '@/api/strategyApi';
import BacktestDialog from '@/components/strategies/BacktestDialog.vue';

const route = useRoute();
const router = useRouter();

const strategy = ref({});
const adjustments = ref([]);
const loading = ref(true);
const backtestDialogVisible = ref(false);

const todayProfit = ref(0);
const cumulativeProfit = ref(0);
const todayTurnoverRate = ref(0);

const getStatusTagType = (status) => {
    switch (status) {
        case 'DRAFT': return 'info';
        case 'UNDER_REVIEW': return '';
        case 'ACTIVE': return 'success';
        case 'REJECTED': return 'danger';
        case 'INACTIVE': return 'warning';
        default: return 'info';
    }
}

const getProfitColor = (profit) => {
    if (profit > 0) return '#F56C6C';
    if (profit < 0) return '#67C23A';
    return '#606266';
};

const goBack = () => {
    router.back();
};

const openBacktestDialog = () => {
    backtestDialogVisible.value = true;
};

onMounted(async () => {
    const strategyId = route.params.id;
    if (strategyId) {
        try {
            const [
                strategyRes,
                adjustmentsRes,
                todayProfitRes,
                cumulativeProfitRes,
                todayTurnoverRateRes
            ] = await Promise.all([
                getStrategyById(strategyId),
                getAdjustmentHistory(strategyId),
                getTodayProfit(strategyId),
                getCumulativeProfit(strategyId),
                getTodayTurnoverRate(strategyId)
            ]);

            strategy.value = strategyRes.data;
            adjustments.value = adjustmentsRes.data;
            todayProfit.value = todayProfitRes.data;
            cumulativeProfit.value = cumulativeProfitRes.data;
            todayTurnoverRate.value = todayTurnoverRateRes.data;

        } catch (error) {
            ElMessage.error('获取策略详情失败: ' + (error.response?.data?.message || error.message));
        } finally {
            loading.value = false;
        }
    }
});
</script>

<style scoped>
.page-container {
    padding: 20px;
}

.mt-4 {
    margin-top: 1.5rem;
}
</style>